package com.xingfei.blog.controller;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.json.ParseException;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.constants.GeneralConstants;
import com.xingfei.blog.dto.UserDTO;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.service.WebArticleService;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.*;
import com.xingfei.blog.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * login
 * Created by yhang on 2017/3/17.
 */
@RequestMapping(value = "/login")
@Controller
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private WebUserService webUserService;

    @Autowired
    private WebArticleService webArticleService;

    private static String Profix_User = "user:";

    @Autowired
    private RedisClusterUtil redisCluster;

    @Value("${spring.activemq.broker-url}")
    private String brokerurl;

    @Value("${spring.activemq.user}")
    private String username;

    @Value("${spring.activemq.password}")
    private String password;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String toLogin(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            try {
                Cookie cookie2 = CookieUtil.getCookie(request, "token");
                if (cookie2 != null) {
                    String token = cookie2.getValue();
                    if (StringUtils.isNotEmpty(token)) {
                        UserVO user = webUserService.getUser4Redis(token);
                        if (user != null) {
                            //保存用户信息到当前线程中
                            UserThreadLocal.set(user);
                            //加载数据
                            this.webUserService.firstToLoad(request, user);
                            return "/index";
                        } else {
                            //删除浏览器cookie
                            Cookie cookie = CookieUtil.getCookie(request, "token");
                            CookieUtil.removeCookie(response, cookie);
                            return "/login/jianyi-login";
                        }
                    }
                } else {
                    return "/login/jianyi-login";
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("跳转登陆异常：", e);

            }
        } else {
            return "/login/jianyi-login";
        }
        return null;
    }

    /**
     * login登陆验证
     */
    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    public @ResponseBody
    JsonResult login(HttpServletRequest request, HttpServletResponse response,
                     @RequestParam(value = "userName") String userName,
                     @RequestParam(value = "password") String password,
                     @RequestParam(value = "remember") String remember) {
        JsonResult jsonResult;
        String ip = IPUtil.getLocalIp(request);
        if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password) && StringUtils.isNotEmpty(remember)) {
            try {
                password = MD5Util.getMD5(DESUtil.decryption(password, GeneralConstants.DES_DECODE_KEY));
                String token = null;
                //登陆验证成功，判断是否自动登录
                if (remember.equals("1")) {
                    token = webUserService.login(userName, password, ip, remember, null);
                    CookieUtil.setCookie(response, "token", token);
                }
                //定义2为qq绑定登陆的标识
                else if (remember.equals("2")) {
                    Cookie cookie = CookieUtil.getCookie(request, "token_qq");
                    if (cookie != null) {
                        String value = cookie.getValue();
                        token = webUserService.login(userName, password, ip, remember, value);
                    }
                }
                //定义3为weibo绑定登陆的标识
                else if (remember.equals("3")) {
                    Cookie cookie = CookieUtil.getCookie(request, "token_weibo");
                    if (cookie != null) {
                        String value = cookie.getValue();
                        token = webUserService.login(userName, password, ip, remember, value);
                    }
                } else if (remember.equals("0")) {
                    token = webUserService.login(userName, password, ip, remember, null);
                    CookieUtil.setCookieDefault(response, "token", token);
                }

                if (StringUtils.isBlank(token)) {
                    //验证失败
                    jsonResult = new JsonResult(false, ErrorConstants.LOGIN_ERROR, "用户名或密码错误");
                } else {
                    UserVO user = webUserService.getUser4Redis(token);
                    //用户信息保存当前线程中
                    UserThreadLocal.set(user);
                    //加载信息
                    webUserService.firstToLoad(request, user);
                    //跳转主界面
                    jsonResult = new JsonResult(false, ErrorConstants.SERVER_SUCCESS, "/index");
                }
            } catch (Exception e) {
                logger.error(e.toString());
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
            }
        } else {
            jsonResult = new JsonResult(false, ErrorConstants.LOGIN_ERROR, "请输入用户名或密码");
        }
        return jsonResult;
    }

    /**
     * 通过token登录
     */
    @GetMapping(value = "/loginByToken")
    public ModelAndView loginByToken(String tk_u) {
        //如果自动跳转失败，则跳转至登录页面
        ModelAndView modelAndView = null;
        if (StringUtils.isNotEmpty(tk_u)) {
            //获取用户信息
            //String userInfo = RedisUtil.get(tk_u, 1);
            String userInfo = redisCluster.get(tk_u);
            try {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(userInfo)) {
                    UserDTO userDTO = JSON.parse(userInfo, UserDTO.class);
                    //转换userVO
                    UserVO userVO = this.webArticleService.buildDataForUser(userDTO);
                    modelAndView = new ModelAndView("/index");
                    modelAndView.addObject("userInfo", userVO);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            modelAndView = new ModelAndView("/login/jianyi-login");
        }
        return modelAndView;
    }

    //退出登陆
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        String token = CookieUtil.getCookie(request, "token").getValue();
        //清除redis缓存
        //RedisUtil.del(Profix_User+token,1);
        redisCluster.del(Profix_User+token);
        //删除浏览器cookie
        Cookie cookie = CookieUtil.getCookie(request, "token");
        CookieUtil.removeCookie(response, cookie);
        return "/login/jianyi-login";
    }

    /**
     * 忘记密码相关
     */
    @RequestMapping("/forgetPassword1")
    public String forgetPassword1() {
        return "/forget/jianyi-forget-password1";
    }

    @RequestMapping(value = "/forgetPassword2", method = RequestMethod.POST)
    public ModelAndView forgetPassword2(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "username") String username, @RequestParam(value = "authcode") String authcode, ModelAndView mv) {

        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(authcode)) {
            //判断验证码
            HttpSession session = request.getSession();
            String s = session.getAttribute(GeneralConstants.JIANYI_BLOG_IMGCODE_SESSION_KEY).toString();
            if (s.equals(authcode.toUpperCase())) {
                mv = new ModelAndView("/forget/jianyi-forget-password2");
            }
            //根据用户名查询
            UserVO userVO = webUserService.getUserByUsername(username);
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(userVO, userDTO);
            //redis缓存
            String ip = IPUtil.getLocalIp(request);
            String token = MD5Util.getMD5(ip + System.currentTimeMillis());
            //校验通过，保存进redis
            try {
                String value = JSON.json(userDTO);
                //30分钟
                //RedisUtil.set(Profix_User + token, value, Integer.valueOf(60 * 30), 1);
                redisCluster.set(Profix_User + token, value, Integer.valueOf(60 * 30));
                //回写cookie
                if (StringUtils.isNotEmpty(token)) {
                    CookieUtil.setCookieDefault(response, "token", token);
                    if (userVO != null) {
                        mv.addObject("userVO", userVO);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mv;
    }

    /**
     * 验证手机短信
     */
    @RequestMapping(value = "/checkMessageCode", method = RequestMethod.POST)
    public ModelAndView checkMessageCode(ModelAndView mv, @RequestParam("username") String username, @RequestParam("authcode_phone") String authcode_phone) {

        //String s = RedisUtil.get(username, null);
        String s = redisCluster.get(username);
        if (StringUtils.isNotEmpty(s) && StringUtils.isNotEmpty(authcode_phone)) {
            if (StringUtils.isEquals(s, authcode_phone)) {
                mv = new ModelAndView("/forget/jianyi-forget-password3");
                //根据用户名查询
                UserVO userVO = webUserService.getUserByUsername(username);
                if (userVO != null) {
                    mv.addObject("userVO", userVO);
                }
                return mv;
            }
        }
        return null;
    }

    /**
     * phone/email 重置密码
     */
    @RequestMapping(value = "/forgetPassword3", method = RequestMethod.POST)
    public @ResponseBody
    JsonResult forgetPassword3(HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password) {
        JsonResult jsonResult;
        try {
            password = MD5Util.getMD5(DESUtil.decryption(password, GeneralConstants.DES_DECODE_KEY));
            //更新密码
            boolean flag = webUserService.updateUserByUsername(username, password);
            if (flag) {
                //设置token
                String ip = IPUtil.getLocalIp(request);
                String token = webUserService.login(username, password, ip, null, null);
                if (StringUtils.isNotEmpty(token)) {
                    CookieUtil.setCookieDefault(response, "token", token);
                    //跳转主界面
                    jsonResult = new JsonResult(false, ErrorConstants.SERVER_SUCCESS, "/login/success");
                } else {
                    jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
                }

            } else {
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
        }
        return jsonResult;
    }

    /**
     * email forget password
     */
    @RequestMapping(value = "/sendMessageCodeByEmail", method = RequestMethod.GET)
    public @ResponseBody
    JsonResult sendMessageCodeByEmail(HttpServletRequest request, @RequestParam("email") String email) {
        JsonResult jsonResult;
        String token = null;
        UserDTO userDTO = new UserDTO();
        try {
            if (StringUtils.isNotEmpty(email)) {
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    Cookie cookie2 = CookieUtil.getCookie(request, "token");
                    if (cookie2 != null) {
                        token = cookie2.getValue();
                    }
                }
                //发送邮件
                boolean sendEmailResult = EMailSenderUtil.sendResetPasswordEmail(email, token);
                //发送邮件成功跳转
                if (sendEmailResult) {
                    //注册成功
                    jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "发送邮件成功，请查收确认！");
                    return jsonResult;
                } else {
                    jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
                }
            } else {
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
        }
        return jsonResult;
    }

    /**
     * 邮件验证
     * @param mv
     * @return
     */
    @RequestMapping("/resetEmailPassword")
    public ModelAndView checkEmailCode(ModelAndView mv, @RequestParam("ak") String token) {
        mv = new ModelAndView("/forget/jianyi-forget-password4");
        if (StringUtils.isNotEmpty(token)) {
            //String s = RedisUtil.get(Profix_User + token, 1);
            String s = redisCluster.get(Profix_User + token);
            try {
                UserDTO userDTO = JSON.parse(s, UserDTO.class);
                if (userDTO != null) {
                    mv.addObject("userVO", userDTO);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return mv;
    }

    /**
     * @param request
     * @return
     */
    @RequestMapping("/success")
    public String thirdLogintoIndex(HttpServletRequest request){
        UserVO user = webUserService.getUser4Redis(request);
        //保存用户信息到当前线程中
        UserThreadLocal.set(user);
        //加载数据
        this.webUserService.firstToLoad(request, user);
        return "index";
    }
}
